﻿using NewLife;
using NewLife.Agent;
using NewLife.Log;
using NewLife.Reflection;
using NewLife.Threading;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace AppStart.Common
{
    class AppService : ServiceBase
    {

        public AppService()
        {
            ServiceName = "AppStarServer";

            var set = Setting.Current;
            if (set.IsNew)
            {

                set.Save();
            }

        }

        ServiceManager _Manager;


        /// <summary>服务启动</summary>
        /// <remarks>
        /// 安装Windows服务后，服务启动会执行一次该方法。
        /// 控制台菜单按5进入循环调试也会执行该方法。
        /// </remarks>
        protected override void StartWork(String reason)
        {
            var set = Setting.Current;
            if (set.Services != null)
            {
                XTrace.WriteLine("Services Length = " + set.Services.Length);
                foreach (var item in set.Services)
                {
                    XTrace.WriteLine("Services {0} {1}", item.FileName, item.Arguments);
                }
            }
            // 应用服务管理
            _Manager = new ServiceManager
            {
                Services = set.Services,

                Log = XTrace.Log,
            };

            _Manager.Start();

            SelfWatch.StartWatch();
            base.StartWork(reason);
        }

        /// <summary>服务停止</summary>
        /// <remarks>
        /// 安装Windows服务后，服务停止会执行该方法。
        /// 控制台菜单按5进入循环调试，任意键结束时也会执行该方法。
        /// </remarks>
        protected override void StopWork(String reason)
        {
            base.StopWork(reason);
            SelfWatch.StopWatch();
            _Manager.Stop(reason);

        }

        public void ShowMachineInfo()
        {
            XTrace.WriteLine("FullPath:{0}", ".".GetFullPath());
            XTrace.WriteLine("BasePath:{0}", ".".GetBasePath());
            XTrace.WriteLine("TempPath:{0}", Path.GetTempPath());

            var mi = MachineInfo.Current ?? MachineInfo.RegisterAsync().Result;

            foreach (var pi in mi.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                XTrace.WriteLine("{0}:\t{1}", pi.Name, mi.GetValue(pi));
            }
        }
    }
}
